package com.example.hangzhou.welbeing.mytestdemoapp.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.transition.Fade;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.example.hangzhou.welbeing.mytestdemoapp.R;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jesse.nativelogger.NLogger;

/**
 * 杭州惟君医疗科技有限公司14
 * Created by 20433 on 2018/3/30
 *
 * @desc 东风山河绿，春已不折柳，繁花看不尽，处处惹人留
 * @desc 佛祖镇楼，bug辟容易
 */

public class MyBloothDemoActivity extends AppCompatActivity {


    @Bind(R.id.button2)
    Button button2;
    @Bind(R.id.button3)
    Button button3;
    @Bind(R.id.textView3)
    TextView textView3;
    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private BleDevice mbleDevice;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
        //TODO 淡入淡出
        getWindow().setEnterTransition(new Fade().setDuration(2000));
        getWindow().setExitTransition(new Fade().setDuration(2000));
        setContentView(R.layout.activity_my_blooth);
        ButterKnife.bind(this);

        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setMaxConnectCount(7)
                .setOperateTimeout(5000);
    }

    @OnClick({R.id.button2, R.id.button3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button2: //打开蓝牙
                checkPermissions(); //todo  开始扫描  ----> 1
                break;
            case R.id.button3:  //关闭蓝牙
                if(mbleDevice != null){
                    if (BleManager.getInstance().isConnected(mbleDevice)) {
                        BleManager.getInstance().disconnect(mbleDevice); //TODO 断开连接
                    }
                }else{
                    BleManager.getInstance().cancelScan();  //todo 2 停止扫描  ----> 2
                }

                break;
        }
    }
    //  .setDeviceMac("")                  // 只扫描指定mac的设备，可选
     //.setServiceUuids(new UUID[]{UUID.fromString("69400001-b5a3-f393-e0a9-e50e24dcca99")})      // 只扫描指定的服务的设备，可选
    private void setScanRule() {
        // todo 扫描的真正方法  --->5
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setServiceUuids(new UUID[]{UUID.fromString("69400001-b5a3-f393-e0a9-e50e24dcca99")})      // 只扫描指定的服务的设备，可选
                .setDeviceName(true)   // 只扫描指定广播名的设备，可选
                .setAutoConnect(false)      // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
    }
    // todo 扫描的方法
    private void startScan() {
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                NLogger.e("TAG","====onScanStarted========"); //todo 这里  提示进度----> 1
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
                NLogger.e("TAG","====onLeScan========");
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
             //todo 这里 取判断连接自己的设备 -------------------------------> 判断你要连接那个设备
                NLogger.e("TAG","====onScanning45========"+bleDevice.getName());
                if(bleDevice.getName().equals("WelBi_3Y1K")){ //WelBi_0008
                    if (!BleManager.getInstance().isConnected(bleDevice)) {  // todo 判断设备是否连接
                        BleManager.getInstance().cancelScan();  //TODO 取消扫描
                        NLogger.e("TAG","====onScanning45取消扫描========");
                        connect(bleDevice);
                    }
                }

            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                NLogger.e("TAG","====onScanFinished========"+scanResultList.size());  //todo 这里  提示----> 2
            }
        });
    }
    private void connect(final BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                NLogger.e("TAG","====onStartConnect========");
            }

            @Override
            public void onConnectFail(BleException exception) {  //todo 这里  结束提示进度----> 1
                NLogger.e("TAG","====onConnectFail========"+exception);
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                NLogger.e("TAG","====45onConnectSuccess========"+bleDevice.getName());
                mbleDevice = bleDevice;
                getBluetoothGatt(bleDevice, gatt);  //todo 这里  结束提示进度----> 1

//                readRssi(bleDevice);
//                setMtu(bleDevice, 23);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                NLogger.e("TAG","====onDisConnected========"+bleDevice.getName()); //结束动画

            }
        });
    }

    private void getBluetoothGatt(final BleDevice bleDevice, final BluetoothGatt gatt) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //todo 这里 逻辑处理-----获取特征值-------------------------->
                for (BluetoothGattService bluetoothGattService : gatt.getServices()) {
                    //NLogger.e("TAG","====getBluetoothGatt111========"+bluetoothGattService.getUuid().toString());
                    if(bluetoothGattService.getUuid().toString().equals("69400001-b5a3-f393-e0a9-e50e24dcca99")){
                        //NLogger.e("TAG","====getBluetoothGatt111=====输入==="+bluetoothGattService.getUuid().toString());
                        for (BluetoothGattCharacteristic bluetoothGattCharacteristic : bluetoothGattService.getCharacteristics()) {
                            //NLogger.e("TAG","====getBluetoothGatt111=====特征==="+bluetoothGattCharacteristic.getUuid().toString());
                            int charaProp =   bluetoothGattCharacteristic.getProperties();
                           // NLogger.e("TAG","====getBluetoothGatt111=====charaProp特征==="+charaProp);
                            if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { // todo 判断是否是  Notify
                                //读取数据
                                MyNotify(bleDevice,bluetoothGattService.getUuid(),bluetoothGattCharacteristic.getUuid());
                            }
                        }
                    }
                }
            }
        }).start();

    }

    private void MyNotify(BleDevice bleDevice, UUID serviceuuid, UUID Characteristicuuid1) {
        //todo 打开通知
        BleManager.getInstance().notify(bleDevice,
                serviceuuid.toString(),
                Characteristicuuid1.toString(),
                new BleNotifyCallback() {

                    @Override
                    public void onNotifySuccess() {
                        NLogger.e("TAG","notify success");  //todo 这里  停止动画
                    }

                    @Override
                    public void onNotifyFailure(final BleException exception) {
                        NLogger.e("TAG","====12========"+exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        String str = new String(data);
                        NLogger.e("TAG","=======33====="+str);
                        textView3.setText(str);

                    }
                });


    }

    /*==============================**/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleManager.getInstance().disconnectAllDevice(); //todo 释放一些资源
        BleManager.getInstance().destroy();

    }

    // todo 权限申请----> 3
    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, "请先打开蓝牙", Toast.LENGTH_LONG).show();
            return;
        }

        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    new AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("当前手机扫描蓝牙需要打开定位功能")
                            .setNegativeButton("取消",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton("前往设置",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                } else {
                    setScanRule();
                    startScan(); //TODO 开始扫描 扫描的方法  ---->4
                }
                break;
        }
    }


    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
            if (checkGPSIsOpen()) {
                setScanRule();
                startScan();
            }
        }
    }

}
